package controller;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/CalledServlet")
public class CalledServlet extends HttpServlet {
    /**
     * 随机点名功能（）从txt文本文件中读取姓名
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = "/Users/manchi520/Desktop/qianfeng/maven-io/src/main/resources/AllNames.txt";
        String s = RandomCalled(url);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(s);
    }

    public String RandomCalled(String url) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(url));
        String line = null;
        List<String> list = new ArrayList<>();
        String s = null;
        //每读一行就进行判断文本是否为空
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        int size = list.size();
        System.out.println(list.size());
        int m =  (int)(Math.random()*(list.size()));
        String s1 = list.get(m);
        System.out.println(s1);
        br.close();
        return s1;
    }
}
